package com.java.socket.tcp.multiclient.multithread.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.Charset;

/**
 * @author xzmeasy
 * @version 1.0
 * @since 星期一 十二月,2018
 */
@SuppressWarnings("Duplicates")
public class ClientSocketExample {

    public static void main(String[] args) {
        try {
            // 创建客户端Socket
            Socket socket = new Socket("localhost", 8888);
            // 从Socket中获取输出流，用于向服务端发送消息
            OutputStream outputStream = socket.getOutputStream();
            PrintWriter printWriter = new PrintWriter(outputStream);
            String message = "来自客户端的消息";
            printWriter.write(message);
            printWriter.flush();
            // 告诉服务段消息已经发送完毕，此句必须有
            socket.shutdownOutput();


            // 从Socket中获取输入流，用于获取服务端的反馈信息
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            StringBuilder info = new StringBuilder();
            while ((len = inputStream.read(bytes)) != -1) {
                info.append(new String(bytes, Charset.forName("utf-8")));
            }
            System.out.println("服务端的反馈信息：" + info.toString());


            // 关闭资源
            inputStream.close();
            printWriter.close();outputStream.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
